// Copyright 2013 Vedran Vuk. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.

package irc

import (
	"strings"
)

// IRCEntity is a helper type providing methods to easily parse out details
// about various types of 'entities' on IRC that are the source or destination
// of messages. For example in a OnMsg (PRIVMSG) event handler it can describe
// both the source of the event as a user in the form of hostmask or a nickname,
// and the target of the event as a channel or yourself as a nickname or a
// hostmask. It is also used with IRCMessage.Prefix().
type IRCEntity string

// Return IRCEntity as string.
func (self *IRCEntity) String() string {
	return string(*self)
}

// Returns true if IRCEntity is an empty string.
func (self *IRCEntity) IsEmpty() bool {
	return len(string(*self)) == 0
}

// Returns true if IRCEntity is a channel name.
func (self *IRCEntity) IsChan() bool {
	return strings.HasPrefix(string(*self), "#") && !self.IsEmpty()
}

// Returns true if IRCEntity is a Hostmask.
func (self *IRCEntity) IsHostmask() bool {
	return strings.IndexAny(string(*self), "!") > -1 &&
		strings.IndexAny(string(*self), "@") > -1
}

// Returns true if IRCEntity is a server name or a nickname.
func (self *IRCEntity) IsName() bool {
	return !self.IsChan() && !self.IsHostmask()
}

// Returns the Nickname if a Hostmask is contained, empty string otherwise.
func (self *IRCEntity) Nickname() string {
	if i := strings.Index(string(*self), "!"); i > 0 {
		return string(*self)[:i]
	} else if len(string(*self)) > 0 {
		return string(*self)
	}
	return ""
}

// Returns the Username if a Hostmask is contained, empty string otherwise.
func (self *IRCEntity) Username() string {
	a := strings.Index(string(*self), "!")
	b := strings.Index(string(*self), "@")
	if a > -1 && b > a {
		return string(*self)[a+1 : b]
	}
	return ""
}

// Returns the Hostname if a Hostmask is contained, empty string otherwise.
func (self *IRCEntity) Hostname() string {
	if i := strings.Index(string(*self), "@"); i > 0 && i+1 < len(*self) {
		return string(*self)[i+1:]
	}
	return ""
}
